$(function() {
	var actionError = $("#actionError").val();
	if ($.trim(actionError) != '') {
		var arrayError = eval("(" + actionError + ")");
		if (arrayError != null) {
			var fieldName = arrayError.fieldName;
			if ($.trim(fieldName) == '') {
				showMessageBox(arrayError);
			} else {
				showMessageTip(arrayError);
			}
		}
	}

	$(document).bind('touchstart', function() {
	});
	
	$(document).on('mouseenter', '[data-title]', function () {
		var $this = $(this);
		var msg = $this.attr("data-title");
		var place = "top";
		if ($this.attr("data-place")) {
			place = $this.attr("data-place");
		}
		showTooltip(msg, $this, place);
	});
	
	$(document).on('click', '.dropdown>ul>li>a', function () {
		var $this = $(this);
		var $li = $this.parent();
		if (!$li.hasClass("disabled") && !$li.hasClass("active")) {
			var text = $this.text();
			var value = $this.attr("data-value");
			var li = $this.parent();
			var dropdown = li.parent().parent();
			dropdown.children("input").val(value).change();
			dropdown.children("button").children(".text").text(text);
			li.addClass("active").siblings().removeClass("active");
		}
	});
	
	$(document).on('setVal', '.dropdown', function (e, val) {
		var dropdown = $(this);
		dropdown.find("ul>li>a").each(function() {
			var dataValue = $(this).attr("data-value");
			if (dataValue == val) {
				$(this).click();
				return;
			}
		});
	});
	
	$(document).on('click', '.form-calendar .btn:not(.disabled)', function () {
		var $this = $(this);
		var $calendar = $this.parent().parent();
		$calendar.children(".form-control").click();
	});
	
	$(document).on('change', '.tab-btn-menu input', function () {
		var $this = $(this);
		var $label = $this.parent();
		var currentActiveOffsetLeft = $label.position().left;
		var slideLineMove = $label.parent().parent().children(".slide-line");
		slideLineMove.animate({
			"left": currentActiveOffsetLeft
		}, 300, 'easeOutQuad');
	});
});

function showErrorMessageBox(msg) {
	var actionError = '{"fieldName":"","message":"' + msg + '","messageDiv":"01"}';
	var arrayError = eval("(" + actionError + ")");
	if ($('#messageBox').length > 0) {
		$('#messageBox').modal('hide');
		setTimeout(function() {
			showMessageBox(arrayError);
		}, 400);
	} else {
		showMessageBox(arrayError);
	}
}

function showInfoMessageBox(msg) {
	var actionError = '{"fieldName":"","message":"' + msg + '","messageDiv":"02"}';
	var arrayError = eval("(" + actionError + ")");
	if ($('#messageBox').length > 0) {
		$('#messageBox').modal('hide');
		setTimeout(function() {
			showMessageBox(arrayError);
		}, 400);
	} else {
		showMessageBox(arrayError);
	}
}

function showMessageBox(arrayError) {
	var messageBoxHtml = '<div class="modal fade" id="messageBox">';
	messageBoxHtml += '<div class="modal-dialog">';
	messageBoxHtml += '<div class="modal-content">';
	messageBoxHtml += '<div class="modal-body">';
	messageBoxHtml += '<ul>';
	if ($.trim(arrayError.message) != '') {
		if (arrayError.messageDiv == '01') {
			messageBoxHtml += '<li class="error">' + arrayError.message + "</li>";
		} else if (arrayError.messageDiv == '02') {
			messageBoxHtml += '<li class="info">' + arrayError.message + "</li>";
		}
	}
	messageBoxHtml += '</ul>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '<div class="modal-footer">';
	messageBoxHtml += '<button type="button" class="btn btn-info" data-dismiss="modal">OK</button>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '</div>';
	$("body").append(messageBoxHtml);
	$('#messageBox').modal('show');
	$('#messageBox').on('hidden.bs.modal', function(e) {
		$(this).remove();
	});
}

function showConfirmBox(message, callback, option) {
	var btnNoText = "取消";
	var btnYesText = "确定";
	if (!!option) {
		if ('btnNoText' in option) {
			btnNoText = option.btnNoText;
		}
		if ('btnYesText' in option) {
			btnYesText = option.btnYesText;
		}
	}
	var messageBoxHtml = '<div class="modal fade" id="confirmBox" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">';
	messageBoxHtml += '<div class="modal-dialog">';
	messageBoxHtml += '<div class="modal-content">';
	messageBoxHtml += '<div class="modal-body">';
	messageBoxHtml += '<ul>';
	messageBoxHtml += '<li class="info">' + message + "</li>";
	messageBoxHtml += '</ul>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '<div class="modal-footer">';
	messageBoxHtml += '<button type="button" class="btn btn-light btn-no" data-dismiss="modal">' + btnNoText + '</button>';
	messageBoxHtml += '<button type="button" class="btn btn-info btn-yes" data-dismiss="modal">' + btnYesText + '</button>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '</div>';
	$("body").append(messageBoxHtml);
	$('#confirmBox').modal('show');
	$('#confirmBox').on('hidden.bs.modal', function(e) {
		$(this).remove();
	});
	$('#confirmBox .btn-no').on('click', function(e) {
		callback('no');
	});
	$('#confirmBox .btn-yes').on('click', function(e) {
		callback('yes');
	});
}

function showErrorMessageTip(msg, field, fieldIdx) {
	var actionError = '{"fieldName":"' + field + '","message":"' + msg + '","messageDiv":"01"}';
	var arrayError = eval("(" + actionError + ")");
	showMessageTip(arrayError, fieldIdx);
}

function showMessageTip(arrayError, fieldIdx) {
	var fieldName = arrayError.fieldName;
	var field;
	if (fieldName.startsWith("#")) {
		field = $(fieldName);
	} else {
		if (!isNaN(parseInt(fieldIdx))) {
			field = $("[name='" + fieldName + "']:eq(" + fieldIdx + ")");
		} else {
			field = $("[name='" + fieldName + "']");
		}
	}
	var msg = arrayError.message;
	var place = "top";
	showTooltip(msg, field, place);
}

function showTooltip(msg, field, place) {
	field.removeAttr("data-toggle").attr("data-toggle", "tooltip");
	field.removeAttr("data-placement").attr("data-placement", place);
	field.removeAttr("data-original-title").attr("data-original-title", msg);
	field.tooltip("show");
	field.focus();
	field.on('hidden.bs.tooltip', function() {
		field.tooltip('dispose');
		field.removeAttr("data-toggle");
		field.removeAttr("data-placement");
		field.removeAttr("data-original-title");
	});
}

function showAlertBox(message) {
	if ($("#alertBox").length > 0) {
		$("#alertBox").alert('close');
	}
	var html = '<div id="alertBox" style="opacity: 0;"><div class="alert alert-dark" role="alert">';
	html += message;
	html += '</div></div>';
	$("body").append(html);
	var alertBox = $("#alertBox");
	alertBox.animate({
		"opacity": 1
	}, 100, 'easeOutQuad', function() {
		setTimeout(function() {
			alertBox.animate({
				"opacity": 0
			}, 100, 'easeOutQuad', function() {
				$("#alertBox").remove();
			});
		}, 1500);
	});
}

function getJson(url, params, callback, showMsg, showLoading, loadingHold) {
	if (showLoading) {
		if (!$(".loading").hasClass("loading")) {
			var loadingBackDrop = createLoadingBackDrop();
			$("body").append(loadingBackDrop);
		}
	}
	$.ajax({
		url: url,
		type: "POST",
		timeout: 10000,
		data: params,
		success: function(data) {
			if ($(".loading").hasClass("loading") && (loadingHold == undefined || loadingHold == null || !loadingHold)) {
				$(".loading").remove();
			}
			if (!data) {
				callback("", "success");
				return;
			}
			var json = eval("(" + data + ")");
			var error = json.error;
			var message = json.message;
			var field = json.field;
			var resultData = json.data;
			if (error) {
				if (showMsg == undefined || showMsg == null || showMsg) {
					if (message != null && message != "") {
						if (field != null && field != "") {
							showErrorMessageTip(message, field);
						} else {
							showErrorMessageBox(message);
						}
					}
				}
				callback("", "error");
			} else {
				if (showMsg == undefined || showMsg == null || showMsg) {
					if (message != null && message != "") {
						if (field != null && field != "") {
							showInfoMessageTip(message, field);
						} else {
							showAlertBox(message);
						}
					}
				}
				callback(resultData, "success");
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			var data = XMLHttpRequest.responseText;
			var json = eval("(" + data + ")");
			var error = json.error;
			var message = json.message;
			var field = json.field;
			var resultData = json.data;
			if (error) {
				if (showMsg == undefined || showMsg == null || showMsg) {
					if (message != null && message != "") {
						if (field != null && field != "") {
							showErrorMessageTip(message, field);
						} else {
							showErrorMessageBox(message);
						}
					}
				}
				callback("", "error");
			} else {
				if (showMsg == undefined || showMsg == null || showMsg) {
					if (message) {
						showErrorMessageBox(message);
					} else {
						showErrorMessageBox("请求超时，请重试");
					}
				}
				if ($(".loading").hasClass("loading")) {
					$(".loading").remove();
				}
				callback("", "error");
			}
		}
	});
}

function getMapData(url, params, callback, showMsg, showLoading, loadingHold, contentType) {
	if (showLoading) {
		if (!$(".loading").hasClass("loading")) {
			var loadingBackDrop = createLoadingBackDrop();
			$("body").append(loadingBackDrop);
		}
	}
	if (!contentType) {
		contentType = "application/x-www-form-urlencoded;charset=UTF-8"
	}
	let requestHeaders = "";
	if (params != undefined && params != null) {
		if ('requestHeaders' in params) {
			requestHeaders = params.requestHeaders;
			delete params.requestHeaders;
		}
	}
	$.ajax({
		url: url,
		type: "POST",
		timeout: 10000,
		data: params,
		contentType : contentType,
		beforeSend: function(request) {
			if (requestHeaders != "") {
				for (let i = 0; i < requestHeaders.length; i++) {
					let requestHeader = requestHeaders[i];
					request.setRequestHeader(requestHeader.key, requestHeader.value);
				}
			}
		},
		success: function(data) {
			if ($(".loading").hasClass("loading") && (loadingHold == undefined || loadingHold == null || !loadingHold)) {
				$(".loading").remove();
			}
			if (!data) {
				callback("", "success");
				return;
			}
			var error = data.error;
			var message = data.message;
			var field = data.field;
			var resultData = data.data;
			if (error) {
				if (showMsg == undefined || showMsg == null || showMsg) {
					if (message != null && message != "") {
						if (field != null && field != "") {
							showErrorMessageTip(message, field);
						} else {
							showErrorMessageBox(message);
						}
					}
				}
				callback("", "error");
			} else {
				if (showMsg == undefined || showMsg == null || showMsg) {
					if (message != null && message != "") {
						if (field != null && field != "") {
							showInfoMessageTip(message, field);
						} else {
							showAlertBox(message);
						}
					}
				}
				callback(resultData, "success");
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			var data = XMLHttpRequest.responseText;
			var json = eval("(" + data + ")");
			var error = json.error;
			var message = json.message;
			var field = json.field;
			var resultData = json.data;
			if (error) {
				if (showMsg == undefined || showMsg == null || showMsg) {
					if (message != null && message != "") {
						if (field != null && field != "") {
							showErrorMessageTip(message, field);
						} else {
							showErrorMessageBox(message);
						}
					}
				}
				callback("", "error");
			} else {
				if (showMsg == undefined || showMsg == null || showMsg) {
					if (message) {
						showErrorMessageBox(message);
					} else {
						showErrorMessageBox("请求超时，请重试");
					}
				}
				if ($(".loading").hasClass("loading")) {
					$(".loading").remove();
				}
				callback("", "error");
			}
		}
	});
}

function getHtml(url, params, wrapper, showLoading, loadingHold, showMsg, callback) {
	if (wrapper == undefined || wrapper == null || wrapper == "") {
		wrapper = "wrapper";
	}
	if (showLoading == undefined || showLoading == null || showLoading) {
		if (!$(".loading").hasClass("loading")) {
			var loadingBackDrop = createLoadingBackDrop();
			$("body").append(loadingBackDrop);
		}
	}
	$("#htmlParams").val("");
	if (params != undefined && params != null) {
		if ('htmlParams' in params) {
			var htmlParams = params.htmlParams;
			var jsonStr = JSON.stringify(htmlParams);
			$("#htmlParams").val(jsonStr);
			delete params.htmlParams;
		}
	}
	var $wrapper = $("#" + wrapper);
	$wrapper.animate({
		"opacity": 0
	}, 300, 'easeOutQuad');
	$.ajax({
		url: url,
		type: "GET",
		timeout: 10000,
		data: params,
		success: function(data) {
			setTimeout(function() {
				if ($(".loading").hasClass("loading") && (loadingHold == undefined || loadingHold == null || !loadingHold)) {
					$(".loading").remove();
				}
				if (data.indexOf("<") == 0) {
					var wait = setInterval(function(){
						if(!$wrapper.is(":animated")){
							clearInterval(wait);
							$wrapper.html(data);
							document.body.scrollTop = document.documentElement.scrollTop = 0;
							var height = $(".container-body").height();
							$(".sidebar-collapse").css("height", height);
							$wrapper.animate({
								"opacity": 1
							}, 300, 'easeOutQuad');
						}
					},100);
					if (!!callback) {
						callback("", "success");
					}
				} else {
					var json = eval("(" + data + ")");
					var error = json.error;
					var message = json.message;
					var field = json.field;
					if (error) {
						if (field == "login") {
							var basePath = $("#basePath").val();
							window.location.href = basePath + "/login";
						}
						if (showMsg == undefined || showMsg == null || showMsg) {
							if (field != null && field != "") {
								showErrorMessageTip(message, field);
							} else {
								showErrorMessageBox(message);
							}
						}
						if (!!callback) {
							callback("", "error");
						}
					} else {
						if (showMsg == undefined || showMsg == null || showMsg) {
							if (message != null && message != "") {
								showInfoMessageBox(message);
							}
						}
						if (!!callback) {
							callback("", "success");
						}
					}
				}
			}, 300);
		},
		error: function() {
			if ($(".loading").hasClass("loading")) {
				$(".loading").remove();
			}
			$wrapper.html("");
			if (showMsg == undefined || showMsg == null || showMsg) {
				showErrorMessageBox("加载超时，请重试");
			}
			if (!!callback) {
				callback("", "error");
			}
		}
	});
}

function createLoadingBackDrop() {
	var html = '';
	html += '<div class="loading modal-backdrop fade in"></div>';
	html += '<div class="loading loading-icon"><div class="icon-box"><div class="line-scale vertical-middle"><div></div><div></div><div></div><div></div><div></div></div></i><div><div>';
	return html;
}

function getHtmlParams(paramName) {
	var retValue = null;
	var htmlParams = $("#htmlParams").val();
	if (htmlParams != null && htmlParams != "") {
		var paramsList = eval("(" + htmlParams + ")");
		for (let i = 0; i < paramsList.length; i++) {
			let params = paramsList[i];
			let key = params.key;
			let value = params.value;
			if (key == paramName) {
				retValue = value;
			}
		}
	}
	return retValue;
}

function clearHtmlParams() {
	$("#htmlParams").val("");
}
//form序列化为json
$.fn.serializeObject = function()
{
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

/**
 * 时间对象的格式化;
 */
Date.prototype.format = function(format) {
	/*
	 * 使用例子:format="yyyy-MM-dd hh:mm:ss";
	 */
	var o = {
		"M+": this.getMonth() + 1, // month
		"d+": this.getDate(), // day
		"H+": this.getHours(), // hour
		"h+": this.getHours(), // hour
		"m+": this.getMinutes(), // minute
		"s+": this.getSeconds(), // second
		"q+": Math.floor((this.getMonth() + 3) / 3), // quarter
		"S": this.getMilliseconds()
		// millisecond
	}
	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
}

function calcDateByDay(date, fmt, days) {
	date.setDate(date.getDate() + days);
	return date.format(fmt);
}

function toDate(date) {
	return new Date(date.replace(/\-/g, "/"));
}

function isMobile() {
	if (window.navigator.userAgent
			.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
		return true; // 移动端
	} else {
		return false; // PC端
	}
}

function isPad() {
	if (window.navigator.userAgent
			.match(/(pad|iPad)/i)) {
		return true;
	} else {
		return false;
	}
}

function maxImg(src, title) {
	var maxImgHtml = '<div class="modal fade" id="maxImgBox">';
	maxImgHtml += '<div class="modal-dialog">';
	maxImgHtml += '<div class="modal-content">';
	maxImgHtml += '<div class="modal-header">';
	maxImgHtml += '<h4 class="modal-title" align="center">';
	if (!!title) {
		maxImgHtml += title;
	} else {
		maxImgHtml += '图片';
	}
	maxImgHtml += '</h4>';
	maxImgHtml += '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
	maxImgHtml += '<span aria-hidden="true">&times;</span>';
	maxImgHtml += '</button>';
	maxImgHtml += '</div>';
	maxImgHtml += '<img src="' + src +'" width="100%">';
	maxImgHtml += '</div>';
	maxImgHtml += '</div>';
	maxImgHtml += '</div>';
	$("body").append(maxImgHtml);
	$('#maxImgBox').modal('show');
	$('#maxImgBox').on('hidden.bs.modal', function(e) {
		$(this).remove();
	});
}

function stopPropagation(e) {
	e = e || window.event;
	if(e.stopPropagation) {
		e.stopPropagation();
	} else {  
		e.cancelBubble = true;
	}
}

function getUrlParams(paramName) {
	var retValue = null;
	var href = window.location.href;
	var url = href.split("?");
	if(url.length > 1){
	var params = url[1].split("&");
		for (let i = 0; i < params.length; i++){
			var param = params[i].split("=");
			let key = param[0];
			let value = param[1];
			if (key == paramName) {
				retValue = value;
			}
		}
	}
	return retValue;
}

